(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    //初始化插件
    function init(o){
        $(document).click(function(){
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                var ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#customscodeselect_'+ids,
                    id: 'customscodeselecttableid_'+ids,
                    data: data3,
                    cols: [[
                        {field: 'customscode', width: 120, title: '海关编码'},
                        {field: 'cuchinesename', width: 120, title: '报关中文品名'},
                        {field: 'cuenglishname', width: 120, title: '报关英文品名'},
                        {field: 'cuelements', width: 120, title: '报关要素'},
                        {field: 'valueaddedtax', width: 120, title: '增值税率'},
                        {field: 'taxrebates', width: 120, title: '退税率'}
                    ]],
                    height: 200
                });

                table.on('row(customscodeselecttable_'+ids+')', function(obj){
                    var data = obj.data;
                    var tabledata = table.cache["moaidetailtableid"];
                    $.each(tabledata,function(index,value){
                        if(value.id==ids){
                            tabledata[index]["customscode"] = data.customscode;
                            tabledata[index]["cuchinesename"] = data.cuchinesename;
                            tabledata[index]["cuenglishname"] = data.cuenglishname;
                            tabledata[index]["cuelements"] = data.cuelements;
                            tabledata[index]["valueaddedtax"] = data.valueaddedtax;
                            tabledata[index]["taxrebates"] = data.taxrebates;

                        }
                    });
                    table.reload('moaidetailtableid',{});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        var ids = $(name).attr("data-id");
        //模糊查询表格并刷新
        table.reload('customscodeselecttableid_'+ids,{where: {
                customscode:value
            }});
    }
})(window.jQuery);



var form = layui.form,
    laydate = layui.laydate,
    upload = layui.upload,
    table = layui.table,
    $ = layui.jquery,
    annexData = [],
    oldId = getQueryVariable("id"),
    sourceType=getQueryVariable("sourceType")
;


lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
//表单初始值，修改时调用
if (oldId != "") {
    form.val("editor-form", {
        "contact": "进入修改",
    })
}

if (sourceType == 1){//新增供应商票
    $("#vendorANDCustomerName").html("厂商名称");
    $("#exportContentANDInvoiceCode").html("报关发票号");
    $("#billingType").html("新增供应商票");
    $("#billingDateName").html("发票收到日期");
    $("#sourceType").val("1");//供应商开票
}else if (sourceType == 2){//新增客户票
    $("#vendorANDCustomerName").html("客户名称");
    $("#exportContentANDInvoiceCode").html("外销合同号");
    $("#billingType").html("新增客户票");
    $("#billingDateName").html("开票日期");
    $("#sourceType").val("2");//客户票
}

//当前时间
let currentDate;

//币种
let currencyInfo = [];
//美元编码
let usdCode = "";
//美元
let usdName = "";
//美金汇率
let usdRate = "";
//美金对人名币汇率
let rmbRate = "";
//开票明细（导入进来的报关明细）
let billingDetailData= [];
//厂商集合
let dataPays=[];
//签约公司集合
let dataCompany=[];
//银行名称集合
let baneNameArr=[];

//页面开始加载
layer.ready(function () {
    //获取所有厂商名称
    $.ajax({
        url:'billing/findAllCustomer2',
        success:function(data){
            if(data.status==200){
                for (let i in data.data){
                    dataPays=data.data;
                    $("#manufacturerCode").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                }
                form.render('select');
            }
        }
    });
    //获取所有签约公司
    $.ajax({
        url:'billing/findAllCompany',
        success:function(data){
            if(data.status==200){
                for (let i in data.data){
                    dataCompany=data.data;
                    $("#billingTowerHeadCode").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                }
                form.render('select');
            }
        }
    });
    /*//获取所有银行名称
    $.ajax({
        url:'billing/getAllBankName',
        success:function(data){
            if(data.status==200){
                for (let i in data.data){
                    baneNameArr=data.data;
                    $("#bankName").append("<option value=\"" + data.data[i] + "\">" + data.data[i] + "</option>");
                }
                form.render('select');
            }
        }
    });*/


        //获取编号,直接回显
        $.ajax({
            url:'billing/getBillingCode',
            success:function(data){
                if(data.status==200){
                    $("#code").val(data.data);
                }
            }
        });

    //获取币种
    $.ajax({
        url:"receivePayment/getCurrencyInfo",
        success:function(data){
            if(data.status == 200){
                currencyInfo = data.data;
                for(let i in data.data){
                    if(data.data[i].englishName == "RMB"){
                        //美元编码
                        usdCode = data.data[i].code;
                        //美元
                        usdName = data.data[i].name;
                        //美元汇率
                        usdRate = data.data[i].exchangeRate;
                        $("#usdRate").val(usdRate);
                    }else if(data.data[i].englishName == "USD"){
                        //获取美金对人名币汇率
                        rmbRate = data.data[i].exchangeRate;
                    }
                    $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                if(usdCode.length > 0){
                    //默认RMB选中
                    $('#currencyCode').val(usdCode);
                    $('#currency').val(usdName);
                    //RMB汇率为1
                    $('#rmbRate').val(1);
                }
                form.render('select');
            }
        }
    });
    //回显注册时间
    currentDate=getNowFormatDate();
    $("#createDate").val(currentDate);

    //获取当前登陆用户名称
    $("#operatorName").val(user.name);
    $("#operatorCode").val(user.code);
});
//获取当前时间，yyyy-MM-dd
function getNowFormatDate() {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let currentDate = year + separator + month + separator + strDate;
    return currentDate;
}
//监听币种下拉框
form.on('select(currencyCode)', function (data) {
    if(data.value === ""){
        return;
    }
    let englishName = getCurrencyInfoByCode(data.value, 1);
    if(englishName == "RMB"){
        //如果选择rmb，则对应rmb汇率为1
        $("#rmbRate").val(1);
        $("#usdRate").val(usdRate);
    }else if(englishName == "USD"){
        //如果选择美元，则对应美金汇率为1
        $("#rmbRate").val(rmbRate);
        $("#usdRate").val(1);
    }else{
        //其它
        let exchangeRate = getCurrencyInfoByCode(data.value, 3);
        $("#usdRate").val(exchangeRate);
        $("#rmbRate").val(rmbRate);
    }
    let name = getCurrencyInfoByCode(data.value, 2);
    $("#currency").val(name);
})

//获取币种信息：code:编码  type(1:获取英文名称 2:获取name 3:获取汇率)
function getCurrencyInfoByCode(code, type){
    for(let i in currencyInfo){
        if(currencyInfo[i].code == code){
            let res = "";
            switch (type) {
                case 1:
                    res = currencyInfo[i].englishName;
                    break;
                case 2:
                    res = currencyInfo[i].name;
                    break;
                case 3:
                    res = currencyInfo[i].exchangeRate;
                    break;
            }
            return res;
        }
    }
    return "";
}


    //监听提交
    form.on('submit(form-element)', function (data) {
        var indexsl = 0;
        var moaidetaildata = table.cache["moaidetailtableid"];
        $.each(moaidetaildata,function(index,value){
           if(typeof (moaidetaildata[index]["goodsNum"])== "undefined" || moaidetaildata[index]["goodsNum"]==""){
                layer.msg("开票明细表第"+(index+1)+"条数量不能为空");
                indexsl++;
                return false;
            }else if(typeof (moaidetaildata[index]["invoiceUnitPrice"])== "undefined" || moaidetaildata[index]["invoiceUnitPrice"]==null){
                layer.msg("开票明细表第"+(index+1)+"条开票单价不能为空");
                indexsl++;
                return false;
            }
        });
        if(indexsl == 0){
            //提交到草稿箱
            let reqData=data.field;
            //附件集合
            reqData["annexReqs"] = table.cache["attachmenttableid"];
            //开票明细集合
            reqData['billingDetailReqList']=moaidetaildata;
            //1：新增，2：修改
            reqData['setType']='1';

            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(reqData),
                url:"billing/add/register",
                success:function (res) {
                    if(res.status==200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/Money/makeoutaninvoice.jsp");
                            parent.intab("views/jsp/Money/makeoutaninvoice.jsp","厂商开票")
                            parent.detab("views/jsp/Money/tpl/newupmakeoutaninvoice.jsp"+(sourceType==''?'':'?sourceType='+sourceType));
                        },1000);
                        return false;
                    }else {
                        layer.msg(res.data, {icon: 6});
                        return false;
                    }

                }
            });
        }
    });

    //--开票明细
    table.render({
        elem: '#moaidetail',
        id: 'moaidetailtableid',
        data: billingDetailData,
        toolbar: '#moaidetailtoolbar',
        cols: [[
            {checkbox: true, fixed: true},
            // {field: 'img', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'saleContractCode', width: 120, title: '销售合同号',sort:true},
            {field: 'stockCode', width: 120, title: '采购单号',sort:true},
            {field: 'goodsCode', width: 120, title: '产品编码',sort:true},
            {field: 'specCode', width: 120, title: '规格编码',sort:true},
            {field: 'goodsSpec', width: 120, title: '规格说明',sort:true},
            {field: 'clientContractNo', width: 120, title: '客户合同号',sort:true},
            {field: 'goodsCname', width: 120, title: '中文名称',sort:true},
            {field: 'goodsEname', width: 120, title: '英文名称',sort:true},
            {field: 'goodsCdesc', width: 120, title: '中文描述',sort:true},
            {field: 'goodsEdesc', width: 120, title: '英文描述',sort:true},
            {field: 'goodsNum', width: 80, title: '数量', edit: 'text'},
            {field: 'invoiceUnitPrice', width: 120, title: '开票单价', edit: 'text',templet: function (d) {
                    let invoiceUnitPricea=new BigNumber(d.invoiceUnitPrice);
                    return invoiceUnitPricea.toFixed(4);
                }},
            {field: 'invoiceSubtotal', width: 120, title: '开票小计',sort:true,templet: function (d) {
                    let num=new BigNumber(d.goodsNum);
                    let invoiceUnitPricea=new BigNumber(d.invoiceUnitPrice);
                    let counta=num.multipliedBy(invoiceUnitPricea).toFixed(2);
                    if (counta==0){
                        counta=0;
                    }
                    return counta;
                }},
            {field: 'color', width: 120, title: '颜色', edit: 'text'},
            {field: 'goodsGross', width: 120, title: '毛重', sort:true},
            {field: 'totalGross', width: 120, title: '毛重小计', sort:true},
            {field: 'netWeight', width: 120, title: '净重', sort:true},
            {field: 'totalNet', width: 120, title: '净重小计', sort:true},
            {field: 'bulk', width: 120, title: '体积', sort:true},
            {field: 'purchaseUnitPrice', width: 120, title: '采购单价', sort:true},
            {field: 'unitCost', width: 120, title: '成本单价',sort:true},
            {field: 'costSubtotal', width: 120, title: '成本小计',sort:true,templet: function (d) {
                    let num=new BigNumber(d.goodsNum);
                    let unitCosta=new BigNumber(d.unitCost);
                    let countb=num.multipliedBy(unitCosta).toFixed(4);
                    if (countb==0){
                        countb=0;
                    }
                    return countb;
                }},
            {field: 'supplyName', width: 120, title: '供应商名称',sort:true},
            {field: 'supplyId', hide:true,title: '供应商ID'},
            {field: 'supplyCode', hide:true,title: '供应商编码'},
            {field:'declarePrice', title:'报关单价', width: 120,sort:true,templet: function (d) {
                    return d.declarePrice==null?0:d.declarePrice
                }},
            {field:'totalPrice', title:'报关金额小计', width: 120,sort:true,templet: function (d) {
                    let num=new BigNumber(d.goodsNum);
                    let declarePricea=new BigNumber(d.declarePrice==null?0:d.declarePrice);
                    let countc=num.multipliedBy(declarePricea).toFixed(4);
                    if (countc==0){
                        countc=0;
                    }
                    return countc;
                }},
            {field: 'productType', width: 120, title: '产品类型',sort:true,templet: function (d) {
                switch (d.productType) {
                    case 1: return '成品'
                    case 2: return '配件'
                    case undefined: return ''
                }
                }},
            {field:'hsCode', title:'海关编码', width: 120,sort:true},
            {field:'billGoodsCname', title:'报关中文品名', width: 140, edit: 'text'},
            {field:'billGoodsEname', title:'报关英文品名', width: 140, edit: 'text'},
            {field: 'hsMemo', width: 120, title: '报关要素', edit: 'text'},
            {field: 'addRate', width: 120, title: '增值税率', edit: 'text'},
            {field: 'backRate', width: 120, title: '退税率', edit: 'text'},
            {field: 'invoiceType', hide: true},
            {field: 'goodsUnit', width: 120, title: '单位', edit: 'text'},
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称', edit: 'text'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号', edit: 'text'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码', edit: 'text'},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#moaidetaileditor'}]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible');
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible');

            let companyCodeStr;
            let totalInvoicedAmount=new BigNumber(0.00);
            for (let i = 0; i < res.data.length; i++) {

                //数据加载完成后，回显报关发票号到from表单
                let declarationInvoiceCode=res.data[0].declarationInvoiceCode;
                //供应商
                let  supplierName=res.data[0].supplyName;
                // let  supplierCode=res.data[0].supplyCode;
                //联系人
                let linker=res.data[0].linker;
                //开票抬头
                let companyName=res.data[0].companyName;
                let companyCode=res.data[0].companyCode;

                getDeclareAnnexList(res.data[i].declareId);

                $("#manufacturerName").val(supplierName);
                // $("#manufacturerCode").val(supplierCode);
                $("#declarationInvoiceCode").val(declarationInvoiceCode);
                $("#contactName").val(linker);
                $("#billingTowerHeadName").val(companyName);
                $("#billingTowerHeadCode").val(companyCode);
                companyCodeStr=companyCode

                let saleContractCode=res.data[0].saleContractCode;
                let carryDetail=res.data[0].carryDetail;
                if(sourceType=="2"){
                    if (carryDetail==="carryDetail"){
                        $("#declarationInvoiceCode").val(res.data[0].billNo);
                    }else{
                        $("#declarationInvoiceCode").val(saleContractCode);
                    }

                }else {
                    if (carryDetail==="carryDetail"){
                        $("#declarationInvoiceCode").val(res.data[0].billNo);
                    }else{
                        $("#declarationInvoiceCode").val(declarationInvoiceCode);
                    }
                    
                }


                //开票总额=开票小计的总和
               let totalPrice=res.data[i].invoiceSubtotal;
                totalInvoicedAmount=totalInvoicedAmount.plus(totalPrice);
            }
            let tempDa=[];
            $.ajax({
                url:"billing/getBankNameByCompanyCode?companyCode="+companyCodeStr,
                async:false,
                success:function(da){
                    if(da.status==200){
                        $('#bankName').append(new Option(da.data, da.data,true));
                        $("#bankName").val(da.data);
                    }
                    form.render('select');
                }
            });

            //开票总额
            $("#totalInvoicedAmount").val(totalInvoicedAmount.toFixed(2));
            //通知金=开票金额
            $("#notificationAmount").val(totalInvoicedAmount.toFixed(2));
            //已开金额--默认0
            $("#openedAmount").val(0);
            // //未开金额=通知金额-已开金额
            $("#uncommittedAmount").val(totalInvoicedAmount.toFixed(2));
            form.render('select');


            hoverOpenImg();//显示大图
            upload.render({
                elem: '.btn_productimg'				//“选择文件”按钮的ID
                ,type:"images"
                ,url: 'https://httpbin.org/post'	//后台接收地址
                ,accept: 'images'				 //允许上传的文件类型
                ,exts: 'png|jpg|gif' 			//设置智能上传图片格式文件
                ,before: function(obj){
                    var thin = this.item[0];
                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){		//在当前ID为“demo2”的区域显示图片
                       $(thin).attr("src",result);
                        var dataid = $(thin).attr("data-id");
                        var tabledata = table.cache["moaidetailtableid"];
                        $.each(tabledata,function(index,value){
                            if(value.id==dataid){
                                tabledata[index]["productimg"] = result;
                            }
                        });
                    });
                }
                ,done: function(res){
                    console.log(res)
                }
            });
            for(var i = 0;i<res.data.length;i++){
                var classs = ".y_"+res.data[i].id;
                $(classs).ySearchSelect(classs);
            }
        }
    });


form.on("select(manufacturerCode_filter)", function(data){
    for(let i in dataPays){
        if(dataPays[i].payeeCode == data.value){
            $("#manufacturerName").val(dataPays[i].payeeName);
        }
    }
});






//监控签约公司下拉框，显示银行名称下拉框
form.on('select(billingTowerHeadCode_filter)', function (data) {
    for(let i in dataCompany){
        if(dataCompany[i].code == data.value){
            $("#billingTowerHeadName").val(dataCompany[i].name);
        }
    }
    $('#bankName').empty();
    let billingTowerHeadCode=$("#billingTowerHeadCode").val();
    if(billingTowerHeadCode!=null){
        $.ajax({
            url:"billing/getBankName",
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:billingTowerHeadCode,
            async:false,
            success:function(data){
                if(data.status==200){
                    for (let i in data.data) {
                        $("#bankName").append("<option value=\"" + data.data[i]+ "\">" + data.data[i] + "</option>");
                    }
                }
                form.render('select');
            }
        });
    }

});


form.on("select(goodsUnit_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["moaidetailtableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["goodsUnit"] = data.value;
        }
    });
});

table.on('edit(moaidetailtable)',function (obj) {
    var old=$(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if((obj.field== "number" || obj.field== "unitprice"|| obj.field== "amountsubtotal")&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
    //数量
    let num=obj.data.goodsNum;
    //开票单价
    let priceInvoiceUnitPrice=obj.data.invoiceUnitPrice;
    //成本单价
    let priceUnitCost=obj.data.unitCost;
    //报关单价
    let priceDeclarePrice=obj.data.declarePrice;

    //开票小计
    obj.data.invoiceSubtotal=parseFloat(num)*parseFloat(priceInvoiceUnitPrice);
    //成本小计
    obj.data.costSubtotal=parseFloat(num)*parseFloat(priceUnitCost);
    //报关金额小计
    obj.data.totalPrice=parseFloat(num)*parseFloat(priceDeclarePrice);
    obj.update(obj.data);
    let tableData = table.cache["moaidetailtableid"];

    let sum=new BigNumber(0.00);
    let amount=new BigNumber(0.00);

    for (let i in tableData) {
        if (!isNumber(tableData[i].invoiceSubtotal)) {
            amount = new BigNumber(0).toFixed(4);
        } else {
            amount = new BigNumber(tableData[i].invoiceSubtotal).toFixed(4);
        }
        sum = sum.plus(amount);
    }
    //开票总额
    $("#totalInvoicedAmount").val(sum.toFixed(4));

    //通知金=开票金额
    $("#notificationAmount").val(sum.toFixed(4));
    //已开金额--默认0
    // //未开金额=通知金额-已开金额
    $("#uncommittedAmount").val(sum.toFixed(4));

});
//计算未开金额
function calculation(){
    //通知金额
    let notificationAmountABig=new BigNumber($("#notificationAmount").val());
    //已开金额
    let openedAmountABig=new BigNumber($("#openedAmount").val());
    if (notificationAmountABig.lt(openedAmountABig)){
        layer.msg("通知金额不能小于已开金额", {icon: 6});
        $("#openedAmount").val(0);
        $("#notificationAmount").val($("#totalInvoicedAmount").val());
        $("#uncommittedAmount").val($("#totalInvoicedAmount").val());
        return;
    }
    //未开金额=通知金额-已开金额 minus
    let uncommittedAmountA=notificationAmountABig.minus(openedAmountABig);
    $("#uncommittedAmount").val(uncommittedAmountA.toFixed(4));
    form.render();
}

    table.on('tool(moaidetailtable)', function (obj) {
        if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                let oldList = table.cache["moaidetailtableid"];
                for (let i = 0; i < oldList.length; i++) {
                    if (oldList[i].tempId==obj.data.tempId) {
                        oldList.splice(i, 1);
                        i--;
                        table.reload('moaidetailtableid',{data : oldList});
                        break;
                    }

                }
                layer.msg("删除成功", {icon: 6});
                 layer.close(index);

            });
        }
    });

    table.on('toolbar(moaidetailtable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'imporcustomsdeclarationform':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/Money/tpl/imporcustomsdeclarationform.jsp'
                });
                break;
            case 'importPurchaseContract':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/Money/tpl/importPurchaseContract.jsp'
                });
                break;
            case 'importExportContract':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/Money/tpl/importExportContract.jsp'
                });
                break;
            case 'importBillExchange':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/Money/tpl/importBillExchange.jsp'
                });
                break;
            case 'importCarryDetail':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/Money/tpl/importCarryDetail.jsp?sourceType='+sourceType
                });
                break;
            case 'del':
                var data=checkStatus.data,delList=[];
                data.forEach(function(n,i){
                    delList.push(n.tempId);
                });
                if(delList!=''){
                    layer.confirm('确定删除所选项吗？',function (index) {
                        var cbList = table.cache["moaidetailtableid"];
                        for(var i = 0;i<cbList.length;i++){
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined"&&item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("moaidetailtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                }else{
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }
let annexList=[];
//获取报关主信息关联的附件,根据报关id
function getDeclareAnnexList(declareId) {
    $.ajax({
        url: 'billDeclare/selectBillFile?type=1&parentId='+declareId,
        type: 'GET',
        success: function (date) {
            annexList=date.data
            table.reload('attachmenttableid', {data:date.data});
        }
    });
}
//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                let id = data.id;
                for (var i = 0; i < annexList.length; i++) {
                    if (annexList[i].id == id) {
                        annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
            });
    }
});

let data2=[];
//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: data2
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}